#!/usr/bin/perl

package Commands::BaseCommand;

use strict;
use warnings;
use Utils qw(dd camel_to_kebab json_decode);
use Carp qw(croak);

use Exporter 'import';

our @EXPORT_OK = qw(new);

# 构造函数
sub new {
    my ($class) = @_;
    my $self = {};
    bless $self, $class;
    return $self;
}

sub usage {
    my $self = shift;
    
    my $subclass = ref($self);
    no strict 'refs';
    my @subclass_actions = @{"${subclass}::actions"};
    my $subclass_name = $subclass;
    $subclass_name =~ s/.*:://;
    $subclass_name =~ (s/Command$//);
    $subclass_name = camel_to_kebab($subclass_name);
    print "  command ${subclass_name} usage: \n";
    foreach my $action (@subclass_actions) {
        print "    ${subclass_name}" 
            . (
                $action->{method} eq "" 
                ? "" 
                : ":"
            ) 
            . sprintf("%-15s", $action->{method}) 
            . "$action->{description}\n";

        if (defined $action->{options}) {
            for my $option (@{$action->{options}}) {
                print "        "
                    . sprintf("%-30s", $option->{name}) 
                    . "$option->{description}\n";
            }
        }
    }
}

sub getAppConfig
{
    my $self = shift;
    my $config_path = $Consts::CONFIG_PATH. $Consts::DS. 'app.json';
    unless (-f $config_path) {
        croak "Config file not found: $config_path";
        return;
    }
    open(my $fh, '<', $config_path) or croak "Failed to open file: $!";
    my $content = do { local $/; <$fh> };
    close($fh);
    my $config = json_decode($content);
    return $config;
}

1;